package com.shaozi.nc.mq.substance;

import java.util.Calendar;

import org.apache.log4j.Logger;
import org.json.JSONObject;

import com.google.gson.JsonSyntaxException;
import com.shaozi.data.mq.business.base.SourceTypeConsts;
import com.shaozi.data.mq.business.bean.MQExchangeData;
import com.shaozi.data.mq.business.bean.MQExchangeRuleBean;
import com.shaozi.data.mq.business.bean.MQSyncItem;
import com.shaozi.data.mq.business.bus.substance.BaseSyncSubstanceHandler;
import com.shaozi.data.mq.business.utils.MqUtil;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.nc.data.model.AttendanceDateInitSyncModel;
import com.shaozi.nc.manage.secretary.AttendanceManage;
import com.shaozi.nc.mq.bean.AttendanceSyncDetailBean;
import com.shaozi.utils.common.BeanUtils;
import com.shaozi.utils.common.JsonUtil;

/**
 * 考勤
 * @author brenx
 *
 */
public class AttendanceSyncSubstance extends BaseSyncSubstanceHandler {

	private final Logger logger = Logger.getLogger(AttendanceSyncSubstance.class);

	public AttendanceSyncSubstance() {

	}

	@SuppressWarnings("rawtypes")
	@Override
	public void substance(MQExchangeData data, JSONObject jsonObj, String destName) throws JsonSyntaxException, SzException {
		MQExchangeRuleBean syncData = (MQExchangeRuleBean) data.getRule();
		if (syncData.getSync() == null) {
			return;
		}
		MQSyncItem syncItem = syncData.getSync();
		int baseType = MqUtil.getBaseSourceType(syncItem.getSourceType());
		switch (baseType) {
		case SourceTypeConsts.Sync.Attendance.Base:
			exchangeTaskData(data, syncData, syncItem, jsonObj);
			break;
		default:
			break;
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void exchangeTaskData(MQExchangeData data, MQExchangeRuleBean syncData, MQSyncItem syncItem,
			JSONObject jsonObj) throws JsonSyntaxException, SzException {
		AttendanceSyncDetailBean detailBean = JsonUtil.toObject(MqUtil.getBizString(jsonObj),
				AttendanceSyncDetailBean.class);
		syncData.setBiz(detailBean);

		AttendanceDateInitSyncModel model = new AttendanceDateInitSyncModel();
		model.setIsSucc(detailBean.getIsSucc());
		Long dataTime = data.getDataTime();
		if (dataTime == null)
			dataTime = System.currentTimeMillis();
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		model.setDateBegin(cal.getTimeInMillis());

		AttendanceManage attendanceManage = (AttendanceManage) BeanUtils.getBean("attendanceManage");
		try {
			attendanceManage.save(data.getCompanyId(), model);
		} catch (SzException e) {
			logger.error(SzException.getStackMessage(e));
		}
	}
}
